package top.heue.utils.base.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.lifecycle.LifecycleEventObserver
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import top.heue.utils.base.helper.activity
import top.heue.utils.log.L
import kotlin.reflect.KProperty

abstract class BasePreference() : PreferenceFragmentCompat() {
    protected val activity by activity()
    abstract val resource: Int
    abstract val name: String
    protected lateinit var root: LinearLayout

    override fun onAttach(context: Context) {
        super.onAttach(context)
        //生命周期日志
        lifecycle.addObserver(LifecycleEventObserver { _, event ->
            L.d("Life", "$this\n${event.name}")
        })
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        root = super.onCreateView(inflater, container, savedInstanceState) as LinearLayout
        return root
    }

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        preferenceManager.sharedPreferencesName = name
        addPreferencesFromResource(resource)
        L.d(name)
    }

    override fun onPreferenceTreeClick(preference: Preference): Boolean {
        if (preference.key != null)
            onClick(preference.key, preference)
        return super.onPreferenceTreeClick(preference)
    }

    protected open fun onClick(key: String, preference: Preference) {

    }
}

/** 返回变量名称*/
object VariableName {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return property.name
    }
    /*operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        update()
    }*/
}